"""
########################################
文件描述：HTTP接口公共方法，file类型尚未完成
接口类型：post，get
编写人：于斌
########################################
"""
# import sys
# sys.path.append('F:\project\测试组\尚盈车联\接口测试\HXF_APITest')
import requests
import logging
import time
import os
# from common.com_excel import Excel


# 定义request函数，传入参数类型应为字典
def request(**kwargs):
    # 将复制传入的字典，赋值给data
    data = kwargs.copy()
    # 拼接接口地址
    api_url = str(data.get('base') + data.get('url'))
    # 将请求数据params和请求头header转为字典类型并赋值
    headers = eval(data.get('header', {}))
    # 定义请求次数和请求成功标记
    attempts = 0
    success = False
    # 判断接口类型post，get
    if data['type'] == 'post':
        # 判断是否为文件类型接口
        if data['file'] != '':
            file_path = '../control/files/'
            files = os.path.join(file_path, str(data.get('file')))
            print('========文件信息========\n', files)
            # 此处try主要防止接口超时，导致脚本终止
            # 执行post请求，最多重试3次,每次间隔5秒
            while attempts < 3 and not success:
                try:
                    file = {
                        'file': (data.get('file', None), open(files, 'rb'), 'image/jpg')
                    }
                    print(api_url)
                    print(file)
                    response = requests.post(url=api_url,
                                             headers=headers,
                                             files=file,
                                             timeout=20)
                    success = True
                    return response
                except Exception as e:
                    print('==============文件打开失败==============', '\n', e)
                    attempts += 1
                    if attempts == 3:
                        logging.error("Timeout for 3 times of execution")
                        break
                    time.sleep(5)

        else:
            file = {}
            params = eval(data.get('params', {}))
            print(params)
            print(type(params))
            while attempts < 3 and not success:
                try:
                    response = requests.post(url=api_url,
                                             params=params,
                                             headers=headers,
                                             files=file,
                                             timeout=20)
                    success = True
                    # print(response.text)
                    return response
                # 当接口超时时，等待5秒，再次重试
                except:
                    attempts += 1
                    if attempts == 3:
                        logging.error("Timeout for 3 times of execution")
                        break
                    time.sleep(5)
    elif data['type'] == 'get':
        params = eval(data.get('params', {}))
        while attempts < 3 and not success:
            try:
                response = requests.get(url=api_url,
                                        params=params,
                                        headers=headers,
                                        timeout=20)
                success = True
                return response
            # 当接口超时时，等待5秒，再次重试
            except:
                attempts += 1
                if attempts == 3:
                    logging.error("Timeout for 3 times of execution")
                    break
                time.sleep(5)
    else:
        logging.error("接口类型填写错误！")


if __name__ == '__main__':
    # case_data = Excel().excel_rd('../testcase/testcase-yubin.xlsx', 'user_info')
    # extract_data = {}
    # print(case_data)
    # for i in case_data:
    #     step = i['step']
    #     params = i.get('params')
    #     res = request(**i)
    data = {'base': 'http://syclimgtest.zhyinfo.cn',
            'url': '/api/TPSB/GetCPSB',
            "params": "{}",
            "file": "1.jpg",
            "header": "{}",
            'type': 'post'}
    a = request(**data).content
    print(a)

    # "header": "{'Content-Type':'application/json'}",
    # "params": "{'loginName': '15851959741', 'password': 'e10adc3949ba59abbe56e057f20f883e', 'phoneType': '1'}",




